package com.fourforfo.fourmall.auth.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fourforfo.common.utils.HttpUtils;
import com.fourforfo.common.utils.R;
import com.fourforfo.common.vo.MemberRespVO;
import com.fourforfo.fourmall.auth.config.OAuth2GiteeProperties;
import com.fourforfo.fourmall.auth.feign.MemberFeignService;
import com.fourforfo.fourmall.auth.vo.GiteeTokenVO;
import com.fourforfo.fourmall.auth.vo.GiteeUserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 *   获取第三方登录的授权码后，直接拦截成功的回调请求
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    OAuth2GiteeProperties properties;

    @Autowired
    MemberFeignService memberFeignService;

    /** 
    * @Description: 从gitee获取token的请求url：
     *              https://gitee.com/oauth/token
     *                 ?grant_type=authorization_code
     *                 &code=81773d03869b98aa29e317af204b806a16ac0a1d2f1f3b4d4fa1d88f35045869
     *                 &client_id=45afedda49ca012d52110466e13785cae92023bec72bc62b002765cf8d21152c
     *                 &redirect_uri=http://fourmall.com/success
     *                 &client_secret=724f93682aa1b0ced0d844b532cb990f84c939c3d4acd0f6a403fbf8ace4869e
    * @Param: [code, attributes, session]
    * @return: java.lang.String
    * @Author: fourforfo
    * @Date: 2022/8/20
    */
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, RedirectAttributes attributes,HttpServletResponse response){

        String redirectUri = "http://auth.fourmall.com/oauth2.0/gitee/success";
        if(!StringUtils.isEmpty(code)){
            //根据code获取accessToken
            Map<String,String> body = new HashMap<>();
            body.put("code",code);
            body.put("grant_type",properties.getGrant_type());
            body.put("client_id",properties.getClient_id());
            body.put("redirect_uri",redirectUri);
            body.put("client_secret",properties.getClient_secret());

            try {
                HttpResponse httpResponse = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", null, null, body);

                if(httpResponse!=null && httpResponse.getStatusLine().getStatusCode()==200){
                    if(httpResponse.getEntity()!=null){
//                        String json = JSON.toJSONString(httpResponse.getEntity());
                        String json = EntityUtils.toString(httpResponse.getEntity());
                        GiteeTokenVO giteeTokenVO = JSON.parseObject(json, GiteeTokenVO.class);

                        //根据accessToken从gitee获取用户信息
                        GiteeUserInfoVO userInfoVO = getUserInfoByAccessToken(giteeTokenVO.getAccess_token());
                        if(userInfoVO!=null){
                            //如果用户是第一次进入本网站，则进行注册，否则登录\
                            R r = memberFeignService.giteeLogin(userInfoVO);
                            if(r.getCode()==0){
                                MemberRespVO respVO = r.getData( new TypeReference<MemberRespVO>() {});
                                log.info("社交登录成功，用户信息为：{}",respVO.toString());

                                /**
                                 * 登录成功调用单点登录成功的相关业务处理，比如生成sessionid等等
                                 * 最后返回redirectUrl加上sessionId
                                 */
                                String url = "http://fourmall.com";
                                return XxlSsoWebController.loginSucess(response,false,url,respVO);
                            }
                            attributes.addFlashAttribute("msg", r.getMsg());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        attributes.addFlashAttribute("msg", "使用码云登录失败，请重新登录！");
        return "redirect:http://auth.fourmall.com/login?redirect_url=http://fourmall.com";

    }


    /**
     * 原
     * @param accessToken
     * @return
     * @throws Exception
     */
//    @GetMapping("/oauth2.0/gitee/success")
//    public String gitee(@RequestParam("code") String code, RedirectAttributes attributes, HttpSession session){
//
//        String redirectUri = "http://auth.fourmall.com/oauth2.0/gitee/success";
//        Map<String ,String> errors = new HashMap<>();
//        if(!StringUtils.isEmpty(code)){
//            //根据code获取accessToken
//            Map<String,String> body = new HashMap<>();
//            body.put("code",code);
//            body.put("grant_type",properties.getGrant_type());
//            body.put("client_id",properties.getClient_id());
//            body.put("redirect_uri",redirectUri);
//            body.put("client_secret",properties.getClient_secret());
//
//            try {
//                HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", null, null, body);
//
//                if(response!=null && response.getStatusLine().getStatusCode()==200){
//                    if(response.getEntity()!=null){
//
//                        String json = EntityUtils.toString(response.getEntity());
//                        GiteeTokenVO giteeTokenVO = JSON.parseObject(json, GiteeTokenVO.class);
//
//                        //根据accessToken从gitee获取用户信息
//                        GiteeUserInfoVO userInfoVO = getUserInfoByAccessToken(giteeTokenVO.getAccess_token());
//                        if(userInfoVO!=null){
//                            //如果用户是第一次进入本网站，则进行注册，否则登录\
//                            R r = memberFeignService.giteeLogin(userInfoVO);
//                            if(r.getCode()==0){
//                                MemberRespVO respVO = r.getData( new TypeReference<MemberRespVO>() {});
//                                log.info("社交登录成功，用户信息为：{}",respVO.toString());
//                                session.setAttribute(AuthConstant.LOGIN_USER,respVO);
//                                return "redirect:http://fourmall.com";
//                            }
//                            errors.put("msg",r.getMsg());
//                        }
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        errors.put("error","使用码云登录失败！");
//        attributes.addFlashAttribute(errors);
//        return "redirect:http://auth.fourmall.com/login.html";
//
//    }

    //https://gitee.com/api/v5/user?access_token=d2ef60e6740e65e19ffc6f0c3938c651
    private GiteeUserInfoVO getUserInfoByAccessToken(String accessToken) throws Exception {
        String host = "https://gitee.com";
        String path = "/api/v5/user";
        Map<String,String> querys = new HashMap<>();
        querys.put("access_token",accessToken);
        //根据accessToken从gitee获取用户信息
        HttpResponse response = HttpUtils.doGet(host,path,"get",null,querys);
        if(response!=null && response.getStatusLine().getStatusCode()==200){
            if(response.getEntity()!=null){
                String json = EntityUtils.toString(response.getEntity());
                GiteeUserInfoVO giteeUserInfoVO = JSON.parseObject(json, GiteeUserInfoVO.class);
                return giteeUserInfoVO;


            }

        }
        return null;
    }

}
